package org.apix;

import java.util.Hashtable;
import java.util.logging.Logger;

import org.apix.configuration.PluginStorageData;
import org.bukkit.entity.Player;

public class CooldownManager {
	@SuppressWarnings("unused")
	private static final Logger log = Apix.log;
	
	private final Apix plugin;
	
	private Hashtable<String, Long> cooldowns;
	
	public CooldownManager(Apix plugin) {
		this.plugin = plugin;
		cooldowns = new Hashtable<String, Long>();
	}
	
	public void setCooldown(Player p, String cooldown) {
		int cooldownAmount = PluginStorageData.getInstance().getCooldown(cooldown);
		
		if(cooldownAmount > 0) {
			cooldowns.put(p.getName() + "." + cooldown, new Long(System.currentTimeMillis()));
		}
	}
	
	public boolean cooldownCheck(Player p, String cooldown) {
		
		long cooldownTimeLeft = this.getCooldownRemaining(p, cooldown);
		if(cooldownTimeLeft > 0) {
			p.sendMessage("Cooldown is in effect. You must wait " + cooldownTimeLeft + " seconds.");
			return false;
		}
		
		this.setCooldown(p, cooldown);
		return true;
		
	}
	
	public long getCooldownRemaining(Player p, String cooldown)
	{
	    	long cooldownRemaining = 0;
//	    	log.info(logPrefix + " checking cooldown for "+cooldown+", player "+p.getName());

	    	int cooldownAmount = PluginStorageData.getInstance().getCooldown(cooldown);
	    	if( cooldownAmount == 0 )
	    		return 0;
	    	
	    	String key = p.getName()+"."+cooldown;
	    	Long cooldownStartTime = cooldowns.get(key);
	    	if( cooldownStartTime != null )
	    	{
//	        	log.info(logPrefix + " cooldown start Time for key "+key+" = "+cooldownStartTime/1000);
	        	
	    		// Compare time
	    		long timeElapsed = (System.currentTimeMillis() - cooldownStartTime)/1000;
	    		
	    		if(timeElapsed > cooldownAmount)
	    			cooldowns.remove(key);    					// cooldown expired, remote it
	    		else
	    			cooldownRemaining = cooldownAmount-timeElapsed;
	    	}
	    	
//	    	log.info(logPrefix + " cooldown remaining for key "+key+" = "+cooldownRemaining);
	    	return cooldownRemaining;
	}

}
